<template>
  <div>
    <Page auto-content-height>
      <FosoTable
        ref="roleTable"
        :columns="columns"
        :request-api="getRoleListData"
        :toolbarbutton-name="$t('sys.role.addRole')"
        @add="openDrawerHandle('add', $event)"
        @delete="DeleteHandle($event)"
        @edit="openDrawerHandle('edit', $event)"
      >
        <template #title>
          <text class="text-[16px]">{{ $t('sys.role.roleList') }} </text>
        </template>
        <template #extraActionButtons="{ row }">
          <!-- 分配权限按钮 -->
          <el-button
            :icon="Lock"
            link
            type="danger"
            @click="assignPermissions(row)"
          />
        </template>
      </FosoTable>
    </Page>

    <!-- 弹窗框 -->
    <Drawer class="w-[35%]" @refresh="reloadTable" />
    <!-- 权限分配 -->
    <Modal class="h-[60%] w-[30%]" />
  </div>
</template>

<script setup lang="tsx">
import type { MenuInfoPlain } from '#/api/sys/model/menuModel';

import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { Lock } from '@element-plus/icons-vue';

import { deleteRole, getRoleList, updateRole } from '#/api/sys/role';
import switchStatus from '#/components/FosoSwitch/index.vue';

import ExtraDrawer from './components/drawer.vue';
import ExtraModal from './components/modal.vue';
// 弹窗连接
const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
});
// 权限分配
const [Modal, modalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: ExtraModal,
});
const roleTableRef = useTemplateRef('roleTable');

// 表格获取数据
const getRoleListData = async (params: any) => {
  const { page = 1, pageSize = 5 } = params;
  const res = await getRoleList({ page, pageSize }); // 调用实际的 API 获取数据

  return {
    total: res.total,
    items: res.data,
  };
};

const columns = computed(() => [
  {
    title: $t('sys.role.roleName'),
    minWidth: 119,
    field: 'name',
  },
  // {
  //   title: $t('sys.role.roleValue'),
  //   field: 'code',
  // },
  {
    title: $t('sys.role.status'),
    field: 'status',
    minWidth: 120,
    slots: {
      default: ({ row }: { row: any }) => {
        return h(switchStatus, {
          status: row.status,
          'onUpdate:status': async (value: any) => {
            await updateRole({
              id: row.id,
              status: value,
            });
            ElMessage.success($t('common.operateSuccess'));
            row.status = value;
          },
        });
      },
    },
  },
  {
    title: $t('sys.role.remark'),
    field: 'remark',
    minWidth: 120,
  },

  // 创建时间
  {
    title: $t('sys.role.createTime'),
    field: 'createdAt',
    minWidth: 120,
    formatter: ['formatDate', 'yyyy-MM-dd'],
  },
  // 操作
  {
    title: $t('sys.role.operation'),
    minWidth: 200,
    slots: { default: 'action' },
  },
]);

/**
 * @author Buke
 * @description 打开弹窗
 * @param {string} type - 操作类型，'edit' 表示编辑，'add' 表示新增。
 * @param {MenuInfoPlain} row - 要编辑的行数据对象，包含角色相关信息。
 * @returns {void}
 */
const openDrawerHandle = (type: string, row?: MenuInfoPlain): void => {
  if (type === 'edit') {
    drawerApi.setState({ title: $t('sys.role.editRole') });
    drawerApi.setData({ type: 'editData', id: row?.id });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
  if (type === 'add') {
    drawerApi.setState({ title: $t('sys.user.addUser') });
    drawerApi.setData({ type: 'addData' });
    drawerApi.open(); // 注意弹框打开需要分开，不能用同一个
  }
};

/**
 * @author Buke
 * @description 删除角色
 * @param {any} row - 要删除的行数据。
 * @returns {void}
 */
async function DeleteHandle(row: MenuInfoPlain): Promise<void> {
  await deleteRole(row.id as number);
  ElMessage.success($t('common.operateSuccess'));
  roleTableRef.value?.gridApi.query();
}

/**
 * @author Buke
 * @description 处理表格数据加载完成后的操作，如更新表格数据。
 * @returns {void}
 */
const reloadTable = (): void => {
  roleTableRef.value?.gridApi.query();
  drawerApi.close();
};

/**
 * @author Buke
 * @description 分配权限
 */
const assignPermissions = (row: MenuInfoPlain) => {
  modalApi.setData({
    id: row.id,
  });
  modalApi.open();
};
</script>
